import os

from utils import read_config as config, k_util, functions_ths, date_util, excel_util, doc_util, json_util
from service import data_service

result_path = os.path.join(config.data_path, 'result', '突破均线')
users_path = os.path.join(config.data_path, 'common', 'users')
config_path = os.path.join(config.data_path, 'common', 'config')
trigger_logs_path = os.path.join(config.data_path, 'logs', '突破均线任务1')

all_content_arr = [
    ['编码', '名称', '开始日期', '结束日期', '开始金额', '最终金额', '操作天数', '持有天数', '持有回报率', '总回报率', '净利润']]  # 生成的excel标题行


#  Var2:=(CLOSE-LLV(LOW,20))/(HHV(HIGH,20)-LLV(LOW,20))*100;
#  Var3:=SMA(SMA(Var2,3,1),3,1)/28.57;
#  Var4:=EMA(Var3,5);
#  Var5:=3*Var3-2*Var4;
#  AA:=CROSS(Var5,Var3) AND Var3<2.1 AND C>O;
#  Var6:=(2*CLOSE+HIGH+LOW)/4;
#  Var7:=LLV(LOW,13);
#  Var8:=HHV(HIGH,13);
#  Var9:=EMA((Var6-Var7)/(Var8-Var7)*100,13);
#  VarA:=EMA(0.667*REF(Var9,1)+0.333*Var9,2);
#  多:Var9,colorred,POINTDOT;
#  空:EMA(0.382*REF(Var9,2)+0.618*Var9,12),colorgreen;
#  DRAWTEXT(CROSS(多,空),多,"始");
#  DRAWTEXT(CROSS(空,多),空,"终");
#  STICKLINE(Var9>VarA,Var9,VarA,6,0),colorred;
#  STICKLINE(Var9<=VarA,Var9,VarA,6,0),COLORFFCC66;
#  STICKLINE(AA,0,30,40,1),coloryellow;
#  STICKLINE(AA,16,29,38,0),colorred;
#  STICKLINE(AA,1,14,38,0),colorred;
#  STICKLINE(AA,15,15,40,1),coloryellow;
#  STICKLINE(AA,30,50,10,0),coloryellow;
#  STICKLINE(AA,53,55,10,1),colorred;
#  STICKLINE(AA,57,59,10,1),colorred;
#  STICKLINE(AA,61,63,10,1),colorred;
#  STICKLINE(AA,65,67,10,1),colorred;
#  STICKLINE(AA,69,75,12,0),colorffcccc;
#  DRAWTEXT(AA,85,'底'),coloryellow;

def get_var2(close, llv20, hhv20):
    # Var2:=(CLOSE-LLV(LOW,20))/(HHV(HIGH,20)-LLV(LOW,20))*100;
    var2_list = []
    len_num = len(close)
    if len_num != len(llv20) or len_num != len(hhv20):
        print('error')
        return 'error'
    for i in range(len_num):
        ci = close[i]
        li20 = llv20[i]
        hi20 = hhv20[i]
        if ci['key'] == li20['key'] == ci['key']:
            if (hi20['value'] - li20['value']) == 0:
                var2 = 0
            else:
                var2 = (ci['value'] - li20['value']) / (hi20['value'] - li20['value']) * 100
            var2_list.append({'key': ci['key'], 'value': var2})
        else:
            print('error')
            return 'error'
    return var2_list


def get_var3(var2):
    #  Var3:=SMA(SMA(Var2,3,1),3,1)/28.57;
    var3_list = []
    ssma = functions_ths.SMA(functions_ths.SMA(var2, 3, 1), 3, 1)
    for v in ssma:
        v['value'] = v['value'] / 28.57
        var3_list.append(v)
    return var3_list


def get_var5(var3, var4):
    #  Var5:=3*Var3-2*Var4;
    var5_list = []
    len_num = len(var3)
    for i in range(len_num):
        vi3 = var3[i]
        vi4 = var4[i]
        key = vi3['key']
        value = 3 * vi3['value'] - 2 * vi4['value']
        var5_list.append({'key': key, 'value': value})
    return var5_list


def get_aa(var5, var3, close):
    #  AA:=CROSS(Var5,Var3) AND Var3<2.1 AND C>O;
    cross = functions_ths.CROSS(var5, var3)
    aa_list = []
    for i in range(len(cross)):
        key = cross[i]['key']
        ci5 = cross[i]['value']
        vi3 = var3[i]['value']
        c = close[i]['value']
        value = ci5 and vi3 < 2.1 and c > 0
        aa_list.append({'key': key, 'value': value})
    return aa_list


def get_var6(close, high, low):
    # Var6:=(2*CLOSE+HIGH+LOW)/4;
    len_num = len(close)
    var6_list = []
    for i in range(len_num):
        key = close[i]['key']
        ci = close[i]['value']
        hi = high[i]['value']
        li = low[i]['value']
        var6_list.append({'key': key, 'value': (2 * ci + hi + li) / 4})
    return var6_list


def get_var9(var6, var7, var8):
    # Var9:=EMA((Var6-Var7)/(Var8-Var7)*100,13);
    v_list = []
    len_num = len(var6)
    for i in range(len_num):
        key = var6[i]['key']
        vi6 = var6[i]['value']
        vi7 = var7[i]['value']
        vi8 = var8[i]['value']
        if (vi8 - vi7) == 0:
            v_list.append({'key': key, 'value': 0})
        else:
            v_list.append({'key': key, 'value': (vi6 - vi7) / (vi8 - vi7) * 100})
    var9_list = functions_ths.EMA(v_list, 13)
    return var9_list


def get_varA(var9):
    #  VarA:=EMA(0.667*REF(Var9,1)+0.333*Var9,2);
    ref = functions_ths.REF(var9, 1)
    len_ref = len(ref)
    len_var9 = len(var9)
    if len_ref != len_var9:
        print('error')
        return 'error'
    v_list = []
    for i in range(len_ref):
        key = ref[i]['key']
        ri6 = ref[i]['value']
        vi9 = var9[i]['value']
        v_list.append({'key': key, 'value': 0.667 * ri6 + 0.333 * vi9})
    vara_list = functions_ths.EMA(v_list, 2)
    return vara_list


def get_kong(var9):
    # 空:EMA(0.382*REF(Var9,2)+0.618*Var9,12),colorgreen;
    ref = functions_ths.REF(var9, 2)
    len_ref = len(ref)
    len_var9 = len(var9)
    if len_ref != len_var9:
        print('error')
        return 'error'
    v_list = []
    for i in range(len_ref):
        key = ref[i]['key']
        ri6 = ref[i]['value']
        vi9 = var9[i]['value']
        v_list.append({'key': key, 'value': 0.382 * ri6 + 0.618 * vi9})
    kong_list = functions_ths.EMA(v_list, 12)
    return kong_list


def deal(a, close, start_date, code, name):
    if name.__contains__('*'):
        return
    content_arr = [['编码', '名称', '日期', '成交价', '买卖', '持有股', '总资本']]  # 生成的excel标题行
    capital_hold = 0
    capital_idle = 100000
    len_num = len(a)
    count = 0  # 持仓天数
    flag = 0
    for i in range(len_num):
        ai = a[i]
        key = a[i]['key']
        if flag == 0 and date_util.diff_days_str(key, start_date) <= 0:
            flag = 1
            continue
        if flag == 1 and ai['value'] == 1:
            if i + 1 >= len_num:
                break
            all = capital_idle + capital_hold
            # 第一天的收盘价格买入
            # 5天内卖出
            print("买" + str(close[i]))
            sp = close[i]['value']
            hand = round(capital_idle / sp / 100)
            capital_hold = hand * sp * 100
            capital_idle = round(capital_idle - capital_hold * 1.00025, 2)
            data = [code, name, key, sp, '买', capital_hold, capital_hold + capital_idle]
            content_arr.append(data)
            for j in range(1, 10):
                count += 1
                if j == 3 or i + j + 1 >= len_num:
                    spj = close[i + j]['value']
                    close_key = close[i + j]['key']
                    capital_deal = hand * spj * 99.975
                    capital_idle = capital_idle + capital_deal
                    capital_hold = 0
                    i = i + j
                    print("卖" + str(close[i]))
                    data = [code, name, close_key, spj, '卖', capital_hold, capital_hold + capital_idle]
                    content_arr.append(data)
                    break
            print(capital_idle + capital_hold - all)
    print(capital_idle + capital_hold)
    doc_name = code + name
    len_len = len(content_arr)
    if len_len == 1:
        return
    excel_util.gen_an_excel(os.path.join(result_path, date_util.get_date_str()), doc_name, '', content_arr)
    # all_content_arr = [['编码', '名称', '开始日期', '开始金额', '最终金额',
    # '操作天数', '持有天数', '回报率', '净利润']]  # 生成的excel标题行
    beg_date = content_arr[1][2]
    end_date = content_arr[len_len - 1][2]
    beg_amt = float(content_arr[1][6])
    end_amt = float(content_arr[len_len - 1][6])
    days = date_util.diff_days_str(beg_date, end_date)
    profit = end_amt - beg_amt
    if days == 0 or count == 0:
        rate_return_hold = 0
        rate_return_all = 0
    else:
        rate_return_hold = round(profit / count, 3)
        rate_return_all = round(profit / days, 4)
    content_arr_row = [code, name, beg_date, end_date, beg_amt, end_amt, days, count, rate_return_hold, rate_return_all,
                       profit]
    all_content_arr.append(content_arr_row)


# 短线狙击
def short_snipe(code, name):
    kas = k_util.get_day_k_all(code)
    if (len(kas) == 0):
        return
    close = functions_ths.parse_x(kas, 'rq', 'sp')
    low = functions_ths.parse_x(kas, 'rq', 'min')
    high = functions_ths.parse_x(kas, 'rq', 'max')
    llv20 = functions_ths.LLV(low, 20)
    hhv20 = functions_ths.HHV(high, 20)
    var2 = get_var2(close, llv20, hhv20)
    var3 = get_var3(var2)
    var4 = functions_ths.EMA(var3, 5)
    var5 = get_var5(var3, var4)
    aa = get_aa(var5, var3, close)  # 底
    var6 = get_var6(close, high, low)
    var7 = functions_ths.LLV(low, 13)
    var8 = functions_ths.HHV(high, 13)
    var9 = get_var9(var6, var7, var8)
    varA = get_varA(var9)
    duo = var9  # 多
    kong = get_kong(var9)  # 空
    shi = functions_ths.CROSS(duo, kong)  # 始
    zhong = functions_ths.CROSS(kong, duo)  # 终
    deal(shi, close, '2020-10-01', code, name)
    # deal(aa, close)


def sniper():
    stock_list = doc_util.get_path_doc_info(os.path.join(config_path, '10.板块前五'))
    # for stock in stock_list:
    #     bp = os.getcwd().split('StockMonitor')[0]
    #     code = stock['code']
    #     source = os.path.join(bp, 'stockMonitorData', 'common', 'datak', 'daykAll', code)
    #     target = os.path.join(bp, 'StockMonitor', 'common', 'datak', 'daykAll', code)
    #     doc_util.copy_doc(source, target)
    #
    #     source = os.path.join(bp, 'stockMonitorData', 'common', 'dayk', code + '.txt')
    #     target = os.path.join(bp, 'StockMonitor', 'common', 'dayk', code + '.txt')
    #     doc_util.copy_doc(source, target)
    for stock in stock_list:
        stock = json_util.to_json(stock)
        short_snipe(stock['code'], stock['name'])
    excel_util.gen_an_excel(os.path.join(result_path, date_util.get_date_str()), '0汇总0', '', all_content_arr)


def compare():
    half = excel_util.get_excel_info(os.path.join(result_path, date_util.get_date_str(), '0汇总半年.xlsx'), '')
    one = excel_util.get_excel_info(os.path.join(result_path, date_util.get_date_str(), '0汇总一年.xlsx'), '')
    one_dict = {}
    half_dict = {}
    content_arr = [['编码', '名称', '一年名次', '半年名次', '差异名次']]  # 生成的excel标题行
    for i in range(1, 698):
        one_row = one[i]
        half_row = half[i]
        one_dict[one_row[0]] = i
        half_dict[half_row[0]] = i
    for key in one_dict:
        name = data_service.stock(key)['name']
        data = [key, name, one_dict[key], half_dict[key], one_dict[key] - half_dict[key]]
        content_arr.append(data)
    excel_util.gen_an_excel(os.path.join(result_path, date_util.get_date_str()), '0对比', '', content_arr)


if __name__ == '__main__':
    # sniper()
    compare()
